﻿using System;
using System.Drawing;
using System.Threading;
using System.Windows.Forms;
using Sedge.Core.Globalization;
using Sedge.UI.Controller;
using Sedge.UI.ViewModel;

namespace Sedge.UI.View
{
	public partial class ScreenshotView : UserControl, ITransferable
	{
		#region Private fields

		private Bitmap _originalBitmap;
		private readonly ScreenshotViewModel _viewModel;
		
		#endregion //Private fields

		#region Constructors

		public ScreenshotView()
		{
			InitializeComponent();
			SetupWindow();
		}

		public ScreenshotView(ScreenshotViewModel viewModel) 
			: this()
		{
			_viewModel = viewModel;
		}
		
		#endregion //Constructors

		#region Private Methods
		
		private void SetupWindow()
		{
			buttonTake.Text = Locale.Strings.ButtonTake;
			buttonEdit.Text = Locale.Strings.ButtonEdit;
			buttonRemove.Text = Locale.Strings.ButtonRemove;
			
			EnableButtonRemove();
		}

		private void ShowForm()
		{
			if (ParentForm != null)
			{
				ParentForm.Show();
				ParentForm.BringToFront();
				ParentForm.Opacity = 100;
			}
		}

		private void HideForm()
		{
			if (ParentForm != null)
			{
				ParentForm.Hide();
				ParentForm.Opacity = 0;

				while (ParentForm.Visible)
				{
					Application.DoEvents();
					Thread.Sleep(100);
				}
			}
		}
      
		private void EnableButtonRemove()
		{
			buttonRemove.Enabled = _originalBitmap != null;
			buttonEdit.Enabled = _originalBitmap != null;
		}

		private Bitmap GetScaledBmp(Image bmp)
		{
			double factor = (double)pictureBox.Width / bmp.Width;
			if (factor * bmp.Height > pictureBox.Height)
			{
				factor = (double)pictureBox.Height / bmp.Height;
			}

			int w = Convert.ToInt32(bmp.Width * factor);
			int h = Convert.ToInt32(bmp.Height * factor);

			Bitmap imageBmp = new Bitmap(pictureBox.Width, pictureBox.Height);
			using (Graphics g = Graphics.FromImage(imageBmp))
			{
				g.DrawImage(bmp, (pictureBox.Width - w) / 2, (pictureBox.Height - h) / 2, w, h);
			}
			return imageBmp;
		}

		#endregion //Private Methods

		#region Event Handlers

		private void buttonTake_Click(object sender, System.EventArgs e)
		{
			Screen screen = Screen.FromControl(this);
			HideForm();
			_originalBitmap = _viewModel.TakeScreenshot(screen);
			ShowForm();

			if (_originalBitmap.Width == 0 || _originalBitmap.Height == 0)
			{
				return;
			}

			pictureBox.Image = GetScaledBmp(_originalBitmap);
			EnableButtonRemove();
		}

		private void buttonRemove_Click(object sender, System.EventArgs e)
		{
			_viewModel.RemoveScreenshot();
			pictureBox.Image = null;
			_originalBitmap = null;

			EnableButtonRemove();
		}

		#endregion //Event Handlers

		public void TransferData()
		{
			// nothing to do
		}

		private void buttonEdit_Click(object sender, EventArgs e)
		{
			AnnotateForm form = new AnnotateForm(_originalBitmap);
			form.ShowDialog();
		}
	}
}
